package br.fbc.facebook.service;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import br.fbc.model.User;
import br.fbc.util.Configurations;
import br.fbc.util.Util;

import com.google.code.facebookapi.FacebookException;
import com.google.code.facebookapi.FacebookJaxbRestClient;
import com.google.code.facebookapi.FacebookJsonRestClient;

public class FacebookService {
	
	String apiKey = "";
	String secretKey = "";
	
	FacebookJsonRestClient client;
	FacebookJaxbRestClient restClient; 
	
	public FacebookService(){
		apiKey = Util.getConfigurations().getApiKey();
		secretKey = Util.getConfigurations().getSecretKey();
		restClient =new FacebookJaxbRestClient(apiKey, secretKey);
		client = new FacebookJsonRestClient(apiKey, secretKey);
	}
	
	public void escreverNoMural(String mensagem, Long userId) throws FacebookException{
		client.stream_publish(mensagem, null, null, null,userId);
	}
	
	public void escreverMuralComPhoto(String mensagem, Long userId, String url) throws FacebookException{
		client.links_post(userId, url, mensagem);
	}
	public JSONObject criarAlbum(Long userId) throws FacebookException{
		return client.photos_createAlbum("qrforfun", userId);		
	}
	public JSONObject incluirFigura(File photo,Long userId) throws FacebookException{
		JSONObject obj = client.photos_upload(userId, photo);
		//JSONObject obj = client.photos_uploadWithCaption(userId, photo, "terra chamando");

		return obj;
	}
	
	public User getInfosFace(Long id) throws FacebookException, JSONException{
		Set<CharSequence> listFields = new HashSet<CharSequence>();
		listFields.add("name");
		List<Long> listUids = new ArrayList<Long>();
		listUids.add(Long.valueOf(id));
		User user = new User();
		
		JSONArray result = client.users_getInfo(listUids, listFields);
		if(result != null){
			
			JSONObject object = result.getJSONObject(0);
			user.setName(object.getString("name"));
			//user.setEmail(object.getString("email"));
			user.setId(id);
			
		}
		
		return user;
		
	}
	public void escreverBoasVindas(Long userId) throws FacebookException, JSONException{
		
		User user = this.getInfosFace(userId);
		client.links_post(userId, Util.getConfigurations().getImagem(), Util.getConfigurations().getBoasVindas(user.getName()));
	}
	
	
	
	
}
